/**
 * 前端分页
 * 前端分页的需求有点多，因此封装起来共后续使用
 */

 function negative(fn) {
    return function(...list) {
        return !fn.apply(null, list);
    }
 }

class ClientPagination {
    data = [];// 总数据
    subList = [];// 当前页数据
    deletedList = [];// 删除的数据
    searchParam = {
        rows: 10,
        page: 1,
        total: 0
    };// 查询参数

    /**
     * 
     * @param {function} filterFunc 
     * @description 查询指定条件的数据
     */
    search(filterFunc) {
        // 定位到第一页
        this.filterFunc = filterFunc;
        this.negativeFilterFunc = negative(filterFunc);
        this.deletedList = [];
        this.searchParam.page = 1;
        let result = this.searchInList(this.searchParam.page);

        this.subList = result.list;
        this.searchParam.total = result.total;
    }

    searchInList(pageIndex) {
        let tempList = [];
        // 当前全部数据都设置为未选中
        this.data.forEach(function(item) {
            item.isInResult = false;
        });
        // 符合查询条件的
        tempList = this.data.filter(this.filterFunc);
        tempList.forEach(function(item) {
            item.isInResult = true;
        });
        // 拼接上不符合条件的
        tempList = tempList.concat(this.data.filter(this.negativeFilterFunc));

        let pageSize = this.searchParam.rows;
        let total = tempList.length;

        let subList = tempList.slice((pageIndex - 1) * pageSize, pageIndex * pageSize);
        return {
            total: total,
            list: subList
        };
    }

    handleDelete(item) {
        for(let i = 0; i < this.data.length; i++) {
            if(this.data[i] === item) {
                this.data.splice(i, 1);
                break;
            }
        }
        
        for(let i = 0; i < this.subList.length; i++) {
            if(this.subList[i].orderId === item.orderId) {
                this.subList.splice(i, 1);
            }
        }

        this.deletedList.push(item);

        // 刷新当前页
        if(this.searchParam.total - 1 <= (this.searchParam.page - 1) * this.searchParam.rows) {
            this.handleCurrentChange(this.searchParam.page - 1);
        } else {
            this.handleCurrentChange(this.searchParam.page);
        }
    }

    handleCurrentChange(pageIndex) {
        this.searchParam.page = pageIndex;
        let result = this.searchInList(this.searchParam.page);
        this.subList = result.list;
        this.searchParam.total = result.total;
    }
}

export default ClientPagination;